<template>
  <div class="container"
       style="white-space: nowrap; height: 100%; display: flex; justify-content: flex-start; align-items: center; margin-bottom: 10px;margin-top: 10px;">
    <h3 style="margin-right: 10px; line-height: 40px; margin-bottom: 0; margin-left: 5px;font-size: 20px; color: #000;font-weight: 600;">追踪服务器</h3>
    <!-- 设置与按钮相同的 line-height -->
    <button class="btn text-white"
            style="background-color: #ffffff; width: 30px; height: 30px; border-radius: 8px; display: flex; justify-content: center; align-items: center; padding: 0; margin: 0;"
            @click="update_trace_status">
      <i class="fas fa-sync" style="font-size: 16px; color: #aba8a8;"></i>
    </button>
  </div>
  <div class="container">
    <!-- 全局重置按钮 -->
    <div class="d-flex justify-content-center mt-2 mb-2">
      <div class="card mx-auto text-center btn bg-primary-heavy" @click="showResetConfirmation"
           style="width: 30%; aspect-ratio:100/2;" :class="{ 'disabled': isClick }">
        <div class="card-body d-flex align-items-center justify-content-center">
          <h5 class="m-0 text-white">全局重置</h5>
        </div>
      </div>
    </div>
<!--    <div style="position: relative; white-space: nowrap; height: 100%;">-->
<!--      <button class="btn bg-primary-heavy text-white"-->
<!--              style="position: absolute; right: 5%; top: 10px;"-->
<!--              @click="update_trace_status">-->
<!--        刷新-->
<!--      </button>-->
<!--    </div>-->

    <!--    <div class="card text-center p-3 m-2">-->
    <!--      <h3 class=" mb-3 mt-3">追踪服务器</h3>-->
    <!--    </div>-->
    <!--     &lt;!&ndash; 按钮 &ndash;&gt;-->
    <!--    <div class="d-flex justify-content-center mt-2 mb-2" >-->
    <!--      <div class="card mx-auto text-center btn bg-primary-heavy"  @click="start_init" style="width: 30%; aspect-ratio:100/2;">-->
    <!--        <div class="card-body d-flex align-items-center justify-content-center" >-->
    <!--          <h5 class="m-0 text-white">初始化</h5>-->
    <!--        </div>-->
    <!--      </div>-->
    <!--    </div>-->

    <!-- 初始化按钮 -->
    <div class="d-flex justify-content-center mt-2 mb-2">
      <div class="card mx-auto text-center btn bg-primary-heavy" @click="showInitConfirmation"
           style="width: 30%; aspect-ratio:100/2;" :class="{ 'disabled': isClick||buttons_status[0] } ">
        <div class="card-body d-flex align-items-center justify-content-center">
          <h5 class="m-0 text-white">初始化</h5>
        </div>
      </div>
    </div>
    <!-- 客户端请求 -->
    <div class="card text-center ms-2 me-4 mt-2 mb-2">
      <div class="card-body">
        <h5 class="">用户状态</h5>
        <div class="table-responsive">
          <table class="table">
            <thead>
            <tr>
              <th scope="col">用户</th>
              <th v-for="(user, index) in TraceClients" :key="'user_' + index" scope="col" @click="showUserInfo(index)">
                {{ user.name }}
              </th>
            </tr>
            </thead>
            <tbody>
            <tr>
              <td>请求状态</td>
              <td class="text-white" v-for="(user, index) in TraceClients" :key="'user_status_' + index"
                  :class="user.status ? 'bg-primary-heavy' : 'bg-secondary-light'" @click="showUserInfo(index)">
                {{ (user.status ? '请求追踪' : '未请求') }}
              </td>
            </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>
    <!-- 按钮 -->
    <div class="d-flex justify-content-center mt-2 mb-2">
      <div class="card mx-auto text-center btn bg-primary-heavy" :class="buttonClass" @click="start_trace"
           style="width: 30%; aspect-ratio: 14/4;">
        <div class="card-body d-flex align-items-center justify-content-center">
          <h5 class="m-0 text-white">开始追踪</h5>
        </div>
      </div>
    </div>
    <p>追踪时间: {{ responseTime }} 秒</p>
    <!-- 追踪服务器状态 -->
    <div class="card text-center  ms-2 me-4 mt-2 mb-2">
      <div class="card-body ">
        <h5 class="">追踪服务器</h5>
        <div class="table-responsive">
          <table class="table">
            <thead>
            <tr>
              <th scope="col">用户</th>
              <th v-for="(user, index) in TraceResult" :key="'user_' + index" scope="col">{{ user.name }}</th>
            </tr>
            </thead>
            <tbody>
            <tr>
              <td>状态</td>
              <td class="text-white" v-for="(user, index) in TraceResult" :key="'user_status_' + index"
                  :class="{ 'bg-primary-heavy': !user.status, 'bg-danger-light': user.status }">
                {{ (user.status ? '恶意' : '诚实') }}
              </td>
            </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>
    <!-- 按钮 -->
    <div class="d-flex justify-content-center mt-2 mb-2">
      <div class="card mx-auto text-center btn bg-primary-heavy" style="width: 30%; aspect-ratio: 14/4;"
           :class="{ 'disabled': isReturnButtonDisabled }" @click="return_trace_result">
        <div class="card-body d-flex align-items-center justify-content-center">
          <h5 class="m-0 text-white">返回结果</h5>
        </div>
      </div>
    </div>

    <!-- 模态窗口 (动效窗口) -->
    <div v-if="isModalVisible" class="modal-overlay">
      <div class="modal-content">
        <div class="spinner"></div>
        <h5 class="text-center  mt-3">处理中，请稍候...</h5>
      </div>
    </div>

  </div>
  <!-- 初始化弹窗 -->
  <div v-if="isInitConfirmationVisible" class="modal">
    <div class="modal-content">
      <h4>初始化</h4>
      <p>您确定要执行初始化操作吗？</p>
      <button class="btn bg-primary-heavy  text-white" @click="start_init">确认</button>
      <button class="btn btn-secondary" @click="cancelInit">取消</button>
    </div>
  </div>
  <!-- 全局重置弹窗 -->
  <div v-if="isResetConfirmationVisible" class="modal">
    <div class="modal-content">
      <h4>全局重置</h4>
      <p>您确定要执行全局重置操作吗？</p>
      <button class="btn bg-primary-heavy  text-white" @click="Reset">确认</button>
      <button class="btn btn-secondary" @click="cancelReset">取消</button>
    </div>
  </div>
  <CustomAlert ref="customAlert" />
</template>

<script setup>
import {ref, computed, onMounted, onUnmounted} from 'vue';
import axios from 'axios';
// import { io } from 'socket.io-client';
import {useStore} from 'vuex';
import CustomAlert from './CustomAlert.vue';

const customAlert=ref(null);
// import Swal from 'sweetalert2';

// const showAlert = (text) => {
//   Swal.fire({
//     text: text,
//     // icon: 'info',
//     showConfirmButton: false,
//     showCancelButton: true,
//     cancelButtonText: '确认',
//     cancelButtonColor: '#253cc2'
//   })
//
// };


// 初始化 TraceClients 和 TraceResult 的默认值
const initialTraceClients = [];
const initialTraceResult = [
  {name: '服务器', id: 'Server', status: false},
];

// 声明 TraceClients 和 TraceResult
const TraceClients = ref([]);
const TraceResult = ref([]);
let responseTime = null;
const buttons_status = ref([false, true, true])

// 设置 axios
const apiBaseUrl = window.webConfig && window.webConfig.ServerTraceBaseUrl;
const apitrace = axios.create({
  baseURL: apiBaseUrl,
  headers: {
    'Content-Type': 'application/json',
  },
});

// WebSocket 设置
// let socket;
// const isConnecting = ref(false);  // 标志连接状态
// const connectWebSocket = () => {
//   if (socket) {
//     console.warn('WebSocket is already connected or connecting');
//     return;  // 如果已经连接或正在连接，直接返回
//   }
//   isConnecting.value = true;  // 设置连接状态
//   socket = io(apiBaseUrl); // 请确保这个 URL 与后端 WebSocket 服务器一致
//
//   socket.on('connect', () => {
//     console.log('WebSocket connected');
//     isConnecting.value = false;  // 重置连接状态
//   });
//
//   socket.on('trace_request', (data) => {
//     let {client_id} = data;
//     const client = TraceClients.value.find(client => client.client_id === client_id);
//     if (client) {
//     client.status = true;
//     saveTraceClientsToSessionStorage(); // 保存更新后的数据到本地存储
//   }
//     console.log('WebSocket connected');
//   });
//
//   socket.on('update_client', (data) => {
//     let client_id = data.client_id;
//     // 在这里根据 client_id 更新 TraceClients
//     const clientIndex = TraceClients.value.findIndex(client => client.client_id === client_id);
//     if (clientIndex !== -1) {
//       TraceClients.value[clientIndex].status = data.status;
//     }
//
//     socket.on('disconnect', () => {
//     console.log('WebSocket disconnected, reconnecting...');
//     isConnecting.value = false;  // 重置连接状态
//     setTimeout(connectWebSocket, 1000);  // 1秒后重连
//   });
//   });
//
//   socket.on('disconnect', () => {
//     console.log('WebSocket disconnected, reconnecting...');
//     setTimeout(connectWebSocket, 1000);
//   });
//
// };

// 从本地存储中获取用户设置
const loadTraceClientsFromSessionStorage = () => {
  const storedTraceClients = JSON.parse(sessionStorage.getItem('TraceClients'));
  if (storedTraceClients) {
    TraceClients.value = storedTraceClients;
  } else {
    TraceClients.value = [...initialTraceClients];
  }

  const storedTraceResult = JSON.parse(sessionStorage.getItem('TraceResult'));
  if (storedTraceResult) {
    TraceResult.value = storedTraceResult;
  } else {
    TraceResult.value = [...initialTraceResult];
  }
};

// 将用户设置保存到本地存储
const saveTraceClientsToSessionStorage = () => {
  sessionStorage.setItem('TraceClients', JSON.stringify(TraceClients.value));
  sessionStorage.setItem('TraceResult', JSON.stringify(TraceResult.value));
};

const showUserInfo = (index) => {
  const user = TraceClients.value[index];
  // showAlert(user.name + "_realm: " + user.client_id + "_userid: " + user.userid);// 在真实应用中，你可以使用自定义的弹窗组件来展示用户信息
  customAlert.value.open(user.name + "_realm: " + user.client_id + "_userid: " + user.userid);
  console.log(`Clicked on column ${index}`);
};

// 初始化函数，向后端请求客户端信息并更新 TraceClients 和 TraceResult
const initializeClients = async () => {
  try {
    const response = await apitrace.post('/init');
    if (response.status === 200) {
      const clients = response.data.clients_simpledata; // 假设后端返回的数据结构

      TraceClients.value = clients.map((client) => ({
        // name: `user${client['id']}`,
        name: client['username'],
        client_id: client['client_id'],
        status: false,
        userid: client['userid'],
        // username : client['username']
      }));
      TraceResult.value = [
        {name: '服务器', id: 'Server', status: false},
        ...clients.map((client) => ({
          name: client['username'],
          id: client['client_id'],
          status: false,
        })),
      ];
      console.log('TraceResult.value:', TraceResult.value);
      saveTraceClientsToSessionStorage();
    }
  } catch (error) {
    console.error('请求客户端信息失败:', error);
  }
};

// 按钮状态赋值
const set_buttons = async (step_status) => {
  if (step_status === "step_none") {
    buttons_status.value = [false, true, true];
  } else if (step_status === "step_init_done") {
    buttons_status.value = [true, false, true];
  } else if (step_status === "step_trace_done") {
    buttons_status.value = [true, true, false];
  } else if (step_status === "step_return_done") {
    buttons_status.value = [true, false, true];
  }
  console.log("buttons_status:", buttons_status.value)
};

// 向后端获取前端状态
const update_trace_status = async () => {
  loadTraceClientsFromSessionStorage();
  try {
    // 发送 Localuser 数据给后端
    const response = await apitrace.get('/trace_status');

    if (response.status === 200) {
      console.log(response.data)
      // 从后端获取并更新 Localuser 信息
      // Localuser.value = response.data.get['localUserInfo']; // 假设后端返回的用户信息在 data.localUserInfo 中
      const clients = response.data.traceClients;
      const results = response.data.traceResult;
      TraceClients.value = clients.map((client) => ({
        // name: `user${client['id']}`,
        name: client['name'],
        client_id: client['client_id'],
        status: client['status'],
        userid: client['userid'],
        // username : client['username']
      }));
      TraceResult.value = results.map((result) => ({
        name: result['name'],
        id: result['client_id'],
        status: result['status'],
      }));
      // 设置按钮状态
      set_buttons(response.data.step_status);
      saveTraceClientsToSessionStorage(); // 保存到 sessionStorage
    }
  } catch (error) {
    console.error('更新用户信息失败:', error);
  }
};

const store = useStore();
const hideSidebar = () => store.commit('hideSidebar');
const showSidebar = () => store.commit('showSidebar');

// 组件挂载时加载用户设置并初始化客户端信息
onMounted(() => {
  hideSidebar();
  loadTraceClientsFromSessionStorage();
  // connectWebSocket();
  update_trace_status();
});

// 组件卸载时保存用户设置到本地存储
onUnmounted(() => {
  showSidebar();
  saveTraceClientsToSessionStorage();
  // if (socket) {
  //   socket.disconnect();
  // }
});

const trueCount = computed(() => TraceClients.value.filter(user => user.status).length);
// const buttonClass = computed(() => trueCount.value <= TraceClients.value.length / 2 ? ' disabled' : 'bg-primary');
const buttonClass = computed(() => {
  const isDisabled = trueCount.value <= TraceClients.value.length / 2;
  const isButtonStatusFalse = buttons_status.value[1];
  return (isDisabled || isButtonStatusFalse) ? 'disabled' : 'bg-primary';
});
const hasEmptyStatus = computed(() => TraceResult.value.some(user => user.status === ''));
// const isReturnButtonDisabled = computed(() => hasEmptyStatus.value);
const isReturnButtonDisabled = computed(() => {
  return hasEmptyStatus.value || buttons_status.value[2];
});

// 定义一个方法来获取 status 为 true 的 client_id
const getActiveClientIds = () => {
  return TraceClients.value
      .filter(client => client.status) // 过滤出 status 为 true 的对象
      .map(client => client.client_id); // 提取 client_id
};

//用于初始化
const isInitConfirmationVisible = ref(false);
const showInitConfirmation = () => {
  isInitConfirmationVisible.value = true;
};
const cancelInit = () => {
  isInitConfirmationVisible.value = false;
};
//用于全局重置
const isResetConfirmationVisible = ref(false);
const showResetConfirmation = () => {
  isResetConfirmationVisible.value = true;
};
const cancelReset = () => {
  isResetConfirmationVisible.value = false;
};

const isModalVisible = ref(false);  // 控制模态窗口显示状态
const isClick = ref(false);  //防止按钮重复点击
const start_init = async () => {
  isInitConfirmationVisible.value = false;
  if (isClick.value) {
    // showAlert('请求正在处理中...');
    await customAlert.value.open("请求正在处理中...");
    return;
  }
  isClick.value = true
  isModalVisible.value = true;  // 显示模态窗口
  try {
    // const activeClientIds = getActiveClientIds();
    // showAlert("追踪服务器开始初始化...")
    await initializeClients();
    const response = await apitrace.post('/initial',);

    if (response.status === 200) {
      if (response.data.status === "error") {
        await customAlert.value.open("尚未有客户端参与学习");
        // showAlert("尚未有客户端参与学习")
      } else {
        // showAlert("追踪服务器初始化完成")
        await customAlert.value.open("追踪服务器初始化完成");
        update_trace_status();
      }
    }
  } catch (error) {
    console.error('请求失败:', error);
  } finally {
    isClick.value = false;
    isModalVisible.value = false;  // 请求完成后关闭模态窗口
  }
};

const Reset = async () => {
  isResetConfirmationVisible.value = false;
  if (isClick.value) {
    await customAlert.value.open('请求正在处理中...');
    // showAlert('请求正在处理中...');
    return;
  }
  isClick.value = true
  isModalVisible.value = true;  // 显示模态窗口
  try {
    // const activeClientIds = getActiveClientIds();
    // showAlert("追踪服务器开始初始化...")
    const response = await apitrace.post('/reset',);
    // await initializeClients();
    if (response.status === 200) {
      update_trace_status();
      await customAlert.value.open("追踪服务器全局重置完成");
      // showAlert("追踪服务器全局重置完成")
    }
  } catch (error) {
    console.error('请求失败:', error);
  } finally {
    isClick.value = false;
    isModalVisible.value = false;  // 请求完成后关闭模态窗口
  }
};

// 点击按钮时发送 POST 请求
const start_trace = async () => {
  if (isClick.value) {
    // showAlert('请求正在处理中...');
    await customAlert.value.open('请求正在处理中...');
    return;
  }
  isClick.value = true;
  isModalVisible.value = true;  // 显示模态窗口
  TraceResult.value.forEach(client => {
    client.status = false;
  });
  const startTime = performance.now(); // 记录开始时间
  try {
    const response = await apitrace.post('/start_trace');

    if (response.status === 200) {
      const unhonest_participants = response.data.unhonest_participants;
      console.log('response.data:', response.data);
      console.log('unhonest_participants:', unhonest_participants);
      unhonest_participants.forEach(index => {
        if (index >= -1 && index < TraceResult.value.length) {
          TraceResult.value[index + 1].status = false;
        }
      });
      update_trace_status();
      saveTraceClientsToSessionStorage();
      loadTraceClientsFromSessionStorage();
      console.log('按钮的响应:', response.data);
      const endTime = performance.now(); // 记录结束时间
      responseTime = (endTime - startTime) / 1000; // 计算响应时间
    }
  } catch (error) {
    console.error('请求失败:', error);
  } finally {
    isClick.value = false;
    isModalVisible.value = false;
  }
};

const return_trace_result = async () => {
  if (isClick.value) {
    // showAlert('请求正在处理中...');
    await customAlert.value.open('请求正在处理中...');
    return;
  }
  isClick.value = true;
  isModalVisible.value = true;  // 显示模态窗口
  try {
    const activeClientIds = getActiveClientIds();
    const response = await apitrace.post('/return_result', {'request_trace_ids': activeClientIds});
    if (response.status === 200) {
      TraceResult.value.forEach(client => {
        client.status = true;
      });
      TraceClients.value.forEach(client => {
        client.status = false;
      });
      // showAlert("已返回追踪结果")
      await customAlert.value.open("已返回追踪结果");
      update_trace_status();
    }
  } catch (error) {
    console.error('请求失败:', error);
  } finally {
    isClick.value = false;
    isModalVisible.value = false;
  }
};

</script>


<style scoped nonce="randomNonceValue">
table {
  width: 100%;
  margin-bottom: 1rem;
  color: #212529;
  border-collapse: separate;
  border-spacing: 1px 2px;
}

.container {
  width: 95%;
  margin: 0 auto;
  height: 100%;
}

.button-card {
  width: 30%;
  aspect-ratio: 100 / 2;
}

.bg-primary-heavy {
  background-color: #152ca8 !important;
}

.bg-secondary-light {
  background-color: #aba8a8 !important; /* 淡灰色 */
}

.bg-danger-light {
  background-color: #a12004 !important; /* 淡灰色 */
}

.btn-secondary.disabled {
  pointer-events: none;
  opacity: 1;
}

.disabled1 {
  pointer-events: none;
  opacity: 1;
}

.bg-primary-light {
  background-color: #5e72e4 !important; /* 淡蓝色 */
}

.bg-secondary-light {
  background-color: #aba8a8 !important; /* 淡灰色 */
}

.btn-secondary.disabled {
  pointer-events: none;
  opacity: 1;
}

.disabled1 {
  pointer-events: none;
  opacity: 1;
}

/*窗口动效*/
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(255, 255, 255, 0.7);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  width: 30%; /* 宽度 */
  aspect-ratio: 16/6;
  background-color: #c9dafc;
  padding: 20px;
  border-radius: 8px;
  text-align: center;
}

.spinner {
  border: 4px solid rgba(255, 255, 255, 0.2);
  border-left-color: #152ca8;
  border-radius: 50%;
  width: 40px;
  height: 40px;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

/*初始化弹窗*/
.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
}

.modal-content {
  background: white;
  padding: 20px;
  border-radius: 5px;
  text-align: center;
}
</style>